#!/bin/bash

    
TEMP=`getopt -o v -l verbose -n "Phrase options error"  -- "$@"`
if [ $? != 0 ]; then
    exit 1
fi

eval set -- "$TEMP" 

while true; do 
    case $1 in
    -v|--verbose)
        verbose=v
        shift;;
    --)
        shift
        break;;
    *)
        echo 'Phrase options error!!!'
        exit 1;;
    esac
done
        

function get_real_dir_path() {
    local dir
    local fname
    local realdir
    while [ $# -gt 0 ]; do
        dir=`dirname $1`
        fname=`basename $1`
        realdir=`realpath $dir`
        echo "$realdir/$fname"
        shift
    done
}

while read -r -p "Input sysroot path:" sysroot;
do
    if [ -z "$sysroot" ]; then
        sysroot=/tmp/sysroot
        echo 'set sysroot to /tmp/sysroot!'
    fi
    if [ ! -e "$sysroot" ]; then
        mkdir -p "$sysroot" || continue
    fi
    break
done



while true; do
    read -r  -p "Input cmd to copy:" cmd
    if [[ "$cmd"  =~ ^(q|quit|Quit|Q)$ ]]; then
        exit 0
    fi
    if which $cmd &> /dev/null; then
        cmd_path=`which --skip-alias $cmd` 
    else
        echo 'Command not found!!!' 1>& 2
        continue
    fi
    dlibs="`ldd $cmd_path |grep -Eo '/[^[:space:]]+'`"
    allfiles="$dlibs
$cmd_path"
    allfiles=`get_real_dir_path $allfiles`
    tar cjhf - $allfiles |tar xj${verbose}f - -C $sysroot
done
